<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关的参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="cat_option">
        <el-col>选择商品分类：
          <!-- 级联选择器 -->
          <el-cascader
            style='width:40%'
            v-model="selectedCats"
            :options="catList"
            :props="cascaderProps"
            clearable
            change-on-select
            expand-trigger="hover"
            @change='doSelectCat'
          >

          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleTabClick"
      >
        <!-- 标签页第一个选项 动态参数many-->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            :disabled='isBtnDisable'
            @click="openAdd"
          >添加参数</el-button>
          <!-- 动态名称 -->
          <el-table
            stripe
            border
            :data='manyParamsData'
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 插槽 -->
              <template slot-scope="s">
                <!-- {{s.row}} -->
                <!-- {{this.theCatID}} -->
                <!-- 展示params的标签 -->
                <el-tag
                  v-for="(item,index) in s.row.attr_vals"
                  :key="index"
                  closable
                  @close=removeAttr(index,s.row)
                >
                  {{item}}
                </el-tag>
                <!-- 添加的标签 动态参数 input和button二显示一  -->
                <el-input
                  v-if="s.row.addInputVisible"
                  class="addInput"
                  v-model="s.row.addInputValue"
                  ref="addInputRef"
                  size="small"
                  @keyup.enter.native="ensureAddInput(s.row)"
                  @blur="ensureAddInput(s.row)"
                >
                </el-input>
                <el-button
                  v-else
                  size="small"
                  @click="showAddInput(s.row)"
                >添加新动态参数</el-button>
              </template>
            </el-table-column>
            <!-- 下标行 -->
            <el-table-column
              type="index"
              label="#"
              width="50px"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
              width="150px"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="250px"
            >
              <template slot-scope="s">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click='openEdit(s.row.attr_id)'
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click='removeParamByID(s.row.attr_id)'
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 标签页第二个选项  静态属性-->
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            :disabled='isBtnDisable'
            @click="openAdd"
          >添加属性</el-button>
          <!-- 静态属性 -->
          <el-table
            stripe
            border
            :data='onlyParamsData'
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="s">
                <el-tag
                  v-for="(item,index) in s.row.attr_vals"
                  :key="index"
                  closable
                >
                  {{item}}
                </el-tag>
                <!-- {{s.row}} -->
                <el-input
                  class="addInput"
                  v-if="s.row.addInputVisible"
                  v-model="s.row.addInputValue"
                  ref="addInputRef"
                  size="small"
                  @keyup.enter.native="ensureAddInput(s.row)"
                  @blur="ensureAddInput(s.row)"
                >
                </el-input>
                <el-button
                  v-else
                  size="small"
                  @click="showAddInput(s.row)"
                >添加新静态属性</el-button>
              </template>
            </el-table-column>
            <!-- 下标行 -->
            <el-table-column
              type="index"
              label="#"
              width="50px"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
              width="150px"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="250px"
            >
              <template slot-scope="s">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click='openEdit(s.row.attr_id)'
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click='removeParamByID(s.row.attr_id)'
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数或者添加静态属性对话框 -->
    <el-dialog
      :title="'添加'+activeTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 验证表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeAddLabel"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureAdd"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+activeTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 验证表单formRules和activeAddLabel共用同一个 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeAddLabel"
          prop="attr_name"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureEdit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      catList: [],
      // 选中的分类ids
      selectedCats: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      activeName: 'many',
      // 动态参数数据
      manyParamsData: [],
      // 静态属性数据
      onlyParamsData: [],
      // 添加框
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加对话框的form
      addForm: {
        attr_name: '',
      },
      editForm: {},
      // form验证规则 验证规则基本都一样 所以不同的对话框可以共用这个
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  // 计算属性
  computed: {
    // 标签页里面的按钮是否被禁用
    isBtnDisable: function () {
      if (this.selectedCats.length > 2) {
        // 错误的写法
        // return this.isBtnDisable=true
        return false
      }
      // return this.isBtnDisable=false
      return true
    },
    // 选中的三级分类ID
    theCatID() {
      if (this.selectedCats.length > 2)
        return this.selectedCats[this.selectedCats.length - 1]
      return null
    },
    // 根据动态还是静态显示对应的对话框提示
    activeTitle() {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    },
    // 根据动态还是静态显示对应的input label提示
    activeAddLabel() {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    },
  },
  methods: {
    // 获取分类数据
    async getCatList() {
      let { data: result } = await this.$axios.get('categories')
      // console.log(result);
      if (result.meta.status !== 200)
        return this.$message.error(result.meta.msg)
      this.catList = result.data
      // console.log(this.catList);
    },
    // 请求分类参数数据
    async getParams() {
      let { data: result2 } = await this.$axios.get(
        `categories/${this.theCatID}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      // console.log(result2)
      if (result2.meta.status !== 200)
        // return this.$message.rror(result2.meta.msg)
        return
      // 请求成功 赋值
      // 对params里面的attr_vals进行加工
      result2.data.forEach((item) => {
        item.attr_vals = item.attr_vals == '' ? [] : item.attr_vals.split(' ')
        // 默认显示按钮
        item.addInputVisible = false
        item.addInputValue = ''
      })
      // console.log(result2.data);
      if (this.activeName === 'many') {
        this.manyParamsData = result2.data
      } else {
        this.onlyParamsData = result2.data
      }
    },
    // 级联选择器选择三级分类的动作
    doSelectCat() {
      // console.log(this.selectedCats)
      // 只允许选择三级分类
      if (this.selectedCats.length < 3) {
        this.selectedCats = []
        this.manyParamsData = []
        this.onlyParamsData = []
        return
      }
      // 选中了三级分类
      // console.log(this.theCatID)
      this.getParams()
    },
    // 标签页被点击时候
    handleTabClick() {
      // console.log(this.activeName)
      this.getParams()
      // console.log(this.params);
    },
    // 打开添加对话框
    openAdd() {
      this.addDialogVisible = true
    },
    // 打开编辑对话框
    async openEdit(id) {
      this.editDialogVisible = true
      // 根据id拿到这一条参数的信息
      let {
        data: res,
      } = await this.$axios.get(
        `categories/${this.theCatID}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 获取成功
      // 这样一个个给editForm赋值太麻烦，不要下面三行的操作
      // this.editForm.attr_name = res.data.attr_name
      // // 保存这一条要改数据id方便下一步修改操作
      // this.editForm.attr_id = id
      this.editForm = res.data
      // console.log(this.editForm)
    },
    // 添加对话框关闭时候
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 确认添加参数
    ensureAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // let id=this.selectedCats[this.selectedCats.length-1];
        // console.log(id);
        let { data: result } = await this.$axios.post(
          `categories/${this.theCatID}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        // console.log(result)
        if (result.meta.status !== 201)
          return this.$message.error(result.meta.msg)
        this.$message.success(result.meta.msg)
        this.getParams()
        this.addDialogVisible = false
      })
    },
    // 确认修改参数
    ensureEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请输入合法的值')
        // 验证通过 发送修改请求
        let { data: res } = await this.$axios.put(
          `categories/${this.theCatID}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 修改成功！
        this.$message.success('修改成功！')
        this.getParams()
        this.editDialogVisible = false
      })
    },
    // 删除参数
    async removeParamByID(id) {
      var res = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((e) => e)
      // console.log(res);
      if (res === 'confirm') {
        let { data: res2 } = await this.$axios.delete(
          `categories/${this.theCatID}/attributes/${id}`
        )
        // console.log(res2);
        if (res2.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message.success(res2.meta.msg)
        this.getParams()
      } else {
        return this.$message.info('已取消删除！')
      }
    },
    // 关闭btn按钮，打开input
    showAddInput(row) {
      row.addInputVisible = true
      // 自动获取焦点
      this.$nextTick((_) => {
        this.$refs.addInputRef.$refs.input.focus()
      })
    },
    // 按下enter或者失去焦点的时候，确认添加新参数
    ensureAddInput(row) {
      // console.log(row.cat_id)
      // 用户如果输入空内容
      if (row.addInputValue.trim() == '') {
        row.addInputVisible = false
        return this.$message.error('请输入有效内容！')
      }
      // 用户输入了真实内容
      row.attr_vals.push(row.addInputValue.trim())
      // console.log(row.attr_vals)
      // 把数组加工成字符串
      row.addInputValue = ''
      // 发送请求
      this.saveAttrVals(row)
    },
    // 保存属性参数 方便调用
    async saveAttrVals(row) {
      let { data: res } = await this.$axios.put(
        `categories/${this.theCatID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          // attr_sel: this.activeName,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 请求成功
      this.$message.success(res.meta.msg)
      row.addInputVisible = false
    },
    // 删除标签
    async removeAttr(i, row) {
      // 根据下标移除属性
      row.attr_vals.splice(i, 1)
      // console.log(row.attr_vals)
      // 发送请求
      this.saveAttrVals(row)
    },
  },
  created() {
    this.getCatList()
  },
}
</script>
<style lang="less" scoped>
.cat_option {
  margin: 15px 0px;
}
.el-tag {
  margin: 10px;
}
.addInput {
  width: 150px;
}
</style>
